package com.df.tank;

import java.awt.*;
import java.awt.image.BufferedImage;

/**
 * 子弹类
 */

public class Bullet {
    private static final int SPEED = 20;
    private int x, y;
    private Dir dir;
    private boolean living = true;
    private TankFrame tankFrame = null;
    private BufferedImage image;
    public static int WIDTH = ImageMgr.bulletD.getWidth();
    public static int HEIGHT = ImageMgr.bulletD.getHeight();
    private Group group = Group.BAD;
    //自身带一个  防止每次都new
    Rectangle rect = new Rectangle();

    public Bullet(int x, int y, Dir dir,Group group, TankFrame tankFrame) {
        this.x = x;
        this.y = y;
        this.dir = dir;
        this.group = group;
        this.tankFrame = tankFrame;
        rect.x = x;
        rect.y = y;
        rect.width = WIDTH;
        rect.height = HEIGHT;
        //new出后直接添加到tankFrame中  不用后续add操作了
        this.tankFrame.bulletList.add(this);
    }

    public void paint(Graphics g) {
        switch (dir) {
            case DOWN:
                image = ImageMgr.bulletD;
                break;
            case UP:
                image = ImageMgr.bulletU;
                break;
            case LEFT:
                image = ImageMgr.bulletL;
                break;
            case RIGHT:
                image = ImageMgr.bulletR;
                break;

        }
        g.drawImage(image, x, y, null);
        if (!living) {
            tankFrame.bulletList.remove(this);
        }
//        Color origin = g.getColor();
//        g.setColor(Color.blue);
//        //圆形
//        g.fillOval(x, y, 10, 10);
        move();
//        g.setColor(origin);
    }

    private void move() {

        switch (dir) {
            case LEFT:
                x -= SPEED;
                break;
            case RIGHT:
                x += SPEED;
                break;
            case UP:
                y -= SPEED;
                break;
            case DOWN:
                y += SPEED;
                break;
            default:
                break;
        }
        if (x <= 0 || y <= 0 || x > tankFrame.getWidth() || y > tankFrame.getHeight()) {
            living = false;
        }
        //更新位置
        rect.x = x;
        rect.y = y;
    }

    /**
     * 是否碰撞校验
     * @param tank
     */
    public void crashWith(Tank tank) {
        //Rectangle 用于碰撞测试  每次都new会产生很多垃圾对象优化
//        Rectangle rectBullet = new Rectangle(this.x, this.y, this.WIDTH, this.HEIGHT);
//        Rectangle rectTank = new Rectangle(tank.getX(), tank.getY(), tank.WIDTH, tank.HEIGHT);
        if (this.group != tank.getGroup() && this.rect.intersects(tank.rect)) {
            //表示两个方形重合  相当于碰撞到一起
            tank.die();
            this.die();
        }
    }

    private void die() {
        living = false;
    }
}
